package be.ad.coffeebreak.web;

import be.ad.coffeebreak.services.ProjectHoursService;
import be.ad.coffeebreak.services.ProjectsService;
import be.ad.coffeebreak.services.UsersService;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * A servlet that delegate the requests to commands.
 *
 * @author Stefan Bangels
 */
public final class DispatchServlet extends HttpServlet {

    @EJB
    protected UsersService usersService;

    @EJB
    protected ProjectsService projectsService;

    @EJB
    protected ProjectHoursService projectHoursService;

    /**
     * Processes the request.
     *
     * @param request  the request
     * @param response the response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get the request uri
        String uri = request.getPathInfo();

        // Create the command factory
        CommandFactory commandFactory = new CommandFactory();
        commandFactory.setServiceLocator(createServiceLocator());

        // Resolve the command
        Command command = commandFactory.createCommand(uri);
        if (command == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "no command found for uri: " + uri);
            return;
        }

        // Execute the command
        String view = command.execute(request, response);
        if (view == null) {
            return;
        }

        // Dispatch the view
        RequestDispatcher dispatcher = request.getRequestDispatcher(view);
        dispatcher.forward(request, response);
    }

    /**
     * Create a service locator.
     *
     * @return the service locator
     */
    private ServiceLocator createServiceLocator() {
        ServiceLocator serviceLocator = new ServiceLocator();
        serviceLocator.setUsersService(usersService);
        serviceLocator.setProjectsService(projectsService);
        serviceLocator.setProjectHoursService(projectHoursService);
        return serviceLocator;
    }

}
